const { writeData, readData, clearData } = require("./data");
const { fileLog } = require("./log");

const handlerMap = {
    "sendMsgReq": function (connection, data) {
        const ip = connection.socket.remoteAddress.replace("::ffff:", "");
        const list = writeData(data.text, ip);
        sendMsg(connection, "sendMsgRes", !!list);

        if (list) {
            broadcast("syncMsgNTF", true, {
                items: list
            });
        }
    },
    "clearMsgReq": function () {
        clearData();
        broadcast("syncMsgNTF", true, {
            items: []
        });
    }
}

function broadcast(name, success = true, data = {}) {
    for (const c of Object.values(connectionMap)) {
        sendMsg(c, name, success, data);
    }
}

function sendMsg(connection, name, success = true, data = {}) {
    connection.sendText(JSON.stringify({
        success,
        name,
        data
    }));
}

function onMessage(connection, text) {
    const msg = JSON.parse(text);
    try {
        handlerMap[msg.name](connection, msg.data);
    } catch (e) {
        fileLog("handle message error", e);
    }
}

module.exports = {
    sendMsg,
    onMessage,
    broadcast
}